import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:wuxu_flutter_lianxi/model/good_info.dart';

import '../../../widget/pull/pull_new_load_widget.dart';
import 'home_bloc.dart';

///
/// 首页
///
class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<StatefulWidget> createState() => HomePageState();
}

class HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin<HomePage>, WidgetsBindingObserver {
  bool _ignore = false;
  HomeBloc _homeBloc = HomeBloc();

  /// 展示刷新loading
  _showRefreshLoading() {
    //TODO: 触发刷新
  }

  requestRefresh() {}

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    _homeBloc.requestRefresh().then((_) {
      //then 传入的是函数
      _showRefreshLoading();
    });
  }

  createItem(context, index) {
    print("createItem：$index,${_homeBloc.pullLoadViewControl.dataList}");
    if (_homeBloc.pullLoadViewControl.dataList.isEmpty) {
      return Container(
        alignment: Alignment.center,
        width: double.infinity,
        height: double.infinity,
        child: Text("empty"),
      );
    }
    GoodInfo goodInfo =
        GoodInfo.fromJson(_homeBloc.pullLoadViewControl.dataList[index]);
    return Container(
      alignment: Alignment.center,
      width: double.infinity,
      height: 80,
      color: index % 2 == 0 ? Colors.grey : Colors.white,
      child: Row(
        children: [
          Container(
            width: 20,
          ),
          Image.network(
            goodInfo.picture!,
            width: 50,
            height: 50,
            errorBuilder: (a, b, c) {
              return Text("图片加载错误");
            },
          ),
          Container(
            width: 10,
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(goodInfo.name ?? ""),
              Text("价格：￥${goodInfo.price}"),
            ],
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    //IgnorePointer 拦截手势的控件。ignoring==true 拦截
    return IgnorePointer(
      ignoring: _ignore,
      child: PullLoadWidget(
        _homeBloc.pullLoadViewControl,
        (context, index) {
          return createItem(context, index);
        },
        loadMoreCallback: () {
          Fluttertoast.showToast(msg: "load more");
        },
        refreshCallback: () {
          Fluttertoast.showToast(msg: "refresh");
        },
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      //当resume时，进行刷新
      _showRefreshLoading();
    }
    super.didChangeAppLifecycleState(state);
  }

  @override
  void dispose() {
    super.dispose();
    _homeBloc.dispose();
  }
}
